#!/usr/bin/python
# -*- coding:utf-8 -*-

import KeywordSearch 
from .. import Util
import urllib,re

class PhotoSearch:
    '''
    #example.(crawling)
    from yi01lib.SearchEngine import Flickr
    
    f=Flickr.PhotoSearch()
    f.HasGeo=True
    results=f.Search(u"Kyoto",300)
    for p in results:
        print p.GetURL()
        print p.PhotoID,p.GetLatLng()

    '''
    def __init__(self):
        self._apiKey=Util.API_Key["Flickr"]
        #self.UserID=None
        self.HasGeo=False
        self.PrivacyFilter=1
    def Search(self,unicodedQuery,n=250):
        return self._search(unicodedQuery.encode("utf-8"),n,1)
    def _search(self,text,n,p):
        self.Text=text
        if n<=250:
            param={
                "method":"flickr.photos.search"
                ,"api_key":self._apiKey
                ,"privacy_filter":str(self.PrivacyFilter)
                ,"per_page":str(n)
                ,"page":str(p)
                ,"content_type":"1"
                ,"text":text
            }
            url='http://www.flickr.com/services/rest/?'+urllib.urlencode(param)
            if self.HasGeo: url+="&has_geo=1"
            xml=Util.Download(url)
            m=re.compile('total="([0-9]+)').search(xml)
            totalCnt=0 if m is None else int(m.group(1))
            searchResults=KeywordSearch.SearchResultCollection(totalCnt)
            
            for mResult in re.compile('<photo (.*?)/>',re.M|re.S).finditer(xml):
                result=mResult.group(1)
                ms=dict()
                for t in ("id","owner","secret","server","farm","title"):
                    m=re.compile(t+'="([^"]+)').search(result)
                    ms[t]=None if m is None else m.group(1)
                searchResults.append(FlickrPhoto(int(ms["id"]),ms["secret"],ms["owner"],ms["title"],int(ms["farm"]),int(ms["server"])))
            return searchResults
        else:
            res1=self._search(text,250,p)
            if res1.TotalCount > p*250:
                res2=self._search(text,n-250,p+1)
                res1.extend(res2)
                del res2
            return res1

def makeURL(photo_id,farm,server,secret,mstb):
    if mstb in "mstb" and len(mstb)==1:
        mstb="_"+mstb
    else:
        mstb=""
    return "http://farm%d.static.flickr.com/%d/%d_%s%s.jpg"%(farm,server,photo_id,secret,mstb)

class FlickrPhoto:
    def __init__(self,photo_id,secret,author,title,farm,server):
        self.PhotoID=photo_id
        self.Author=author
        self.Title=title

        self._secret=secret
        self._farm=farm
        self._server=server
        
    def GetURL(self,size="o"):
        return makeURL(self.PhotoID,self._farm,self._server,self._secret,size)
    
    def GetLatLng(self):
        url="http://www.flickr.com/services/rest/?method=flickr.photos.geo.getLocation&api_key=%s&photo_id=%d"%(Util.API_Key["Flickr"],self.PhotoID)
        xml=Util.Download(url)
        m=re.compile('<location latitude="([^"]+)" longitude="([^"]+)"',re.M|re.S).search(xml)
        if m is None :
            return None
        else:
            return (m.group(1),m.group(2))
    
    def GetTags(self):
        url="http://www.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=%s&photo_id=%d"%(Util.API_Key["Flickr"],self.PhotoID)
        xml=Util.Download(url)
        tags=[]
        for mTag in re.compile('<tag [^>]+>(.*?)</tag>',re.M|re.S).finditer(xml):
            tag=mTag.group(1)
            tags.append(tag)

        return tags